package com.fowo.api.pda.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.common.model.R;
import com.fowo.api.controller.purchase.dto.purchaseArgsDTO;
import com.fowo.api.entity.PurchaseOrder;
import com.fowo.api.entity.PurchaseOrderProduct;
import com.fowo.api.entity.WarehouseBin;
import com.fowo.api.model.receipt.ReceiptVo;
import com.fowo.api.model.receipt.product.ReceiptProductItemVo;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.pda.service.PdaReceiptService;
import com.fowo.api.service.ReceiptService;
import com.fowo.api.service.impl.PurchaseOrderProductServiceImpl;
import com.fowo.api.service.impl.PurchaseOrderServiceImpl;
import com.fowo.api.service.impl.StockInServiceImpl;
import com.fowo.api.service.impl.WarehouseBinServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PdaReceiptServiceImpl implements PdaReceiptService {

    @Resource
    private ReceiptService receiptService;
    @Resource
    private PurchaseOrderServiceImpl purchaseOrderService;
    @Resource
    private WarehouseBinServiceImpl warehouseBinService;
    @Resource
    protected PurchaseOrderProductServiceImpl purchaseOrderProductService;
    @Resource
    private StockInServiceImpl stockInService;

    @Transactional(rollbackFor = Exception.class)
    @Override
   public void receiptReceipt(ReceiptVo model) throws Exception {
       model.setStatus("1");
       Integer allTotalStorage = 0;
       for(ReceiptProductItemVo item : model.getReceiptList()){
           allTotalStorage += item.getReceiptNum().intValue();
           item.setNoQcNum(item.getReceiptNum());
           item.setLowQuality(item.getReceiptNum());
           item.setWaitNum(item.getWaitNum()-item.getReceiptNum().intValue());
       }
       model.setAllTotalStorage(allTotalStorage);
       //更新数据
       receiptService.update(model);

       Long stickInId = createStockIn(model);

        //审核入库单
        stockInService.ruku3(stickInId);
    }

    public Long createStockIn(ReceiptVo model) throws Exception {
        PurchaseOrder purchaseOrder = purchaseOrderService.getById(model.getDocRelate());

        //新增入库单和入库单子表
        StockInVo stock=new StockInVo();
        stock.setWarehouse(model.getWarehouse());//设置仓库
        stock.setSupplier(model.getSupplier());//设置供应商
        stock.setReceiptType("RK002");
//        stock.setAStatus("pending");
        stock.setAStatus("completed");
        stock.setStatus("1");
        stock.setAddType("1");
        stock.setRemarks(model.getRemarks());
        stock.setFreight(model.getFreight());//运费
        stock.setOtherExpenses(model.getOtherExpenses());//其他费用
        stock.setWarehousingDate(new Date());//入库时间
        //stock.setWarehousingDate(purchaseArgs.getToMap().getReceiptDate()!=null?LocalDateUtils.toDate(purchaseArgs.getToMap().getReceiptDate(),LocalDateUtils.DATE_PATTERN):new  Date());//入库时间
        stock.setProductType("1");//成品
        stock.setCostAllocationType("1");

        stock.setCgUid(model.getBuyer());
        stock.setGenerateAp("0");
        stock.setPurchasingOrg(purchaseOrder.getPurchasesOrg());
        stock.setNeedOrg(purchaseOrder.getSettlementOrg());
        stock.setWarehousingDate(new Date());
        //stock.setTotalNum();//总数量
        stock.setAssociatedPo(model.getOrderSn());//收货单号
        stock.setPurchaseOrderCode(purchaseOrder.getPurchaseOrderCode());//采购单号
        List<StockInProductItemVo> productList = new ArrayList<>();
        //查询库位
        WarehouseBin warehouseBin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                .eq(WarehouseBin::getWarehouseId, stock.getWarehouse())
                .eq(WarehouseBin::getStorageBin, "待检暂存"));

        for(ReceiptProductItemVo item : model.getReceiptList()){
//            PurchaseOrderProduct purchaseOrderProduct = purchaseOrderProductService.getById(childrenDTO.getFromMap().getId());
//            //修改可退货数量
//            purchaseOrderProduct.setCrossChecking(purchaseOrderProduct.getCrossChecking()!=null?purchaseOrderProduct.getCrossChecking()+childrenDTO.getToMap().getReceiptNum():childrenDTO.getToMap().getReceiptNum());
//            if(purchaseOrderProduct.getQuantityReceive()!=null){
//                if(purchaseOrderProduct.getQuantityReceive().intValue()<0){
//                    purchaseOrderProduct.setQuantityReceive(0);
//                }
//                if(purchaseOrderProduct.getQuantityReceived().intValue()>purchaseOrderProduct.getApplicationNum().intValue()){
//                    purchaseOrderProduct.setApplicationNum(purchaseOrderProduct.getQuantityReceived());
//                }
//            }
            StockInProductItemVo stockInProductItemVo=new StockInProductItemVo();
//            stockInProductItemVo.setUnitPrice(purchaseOrderProduct.getUnitPrice());
            stockInProductItemVo.setProductId(item.getProductId());
//            stockInProductItemVo.setPurchaseOrderProductId(childrenDTO.getFromMap().getId());
            stockInProductItemVo.setShopId(item.getShopId());
            stockInProductItemVo.setSku(item.getSku());
            stockInProductItemVo.setFnsku(item.getFnsku());
            stockInProductItemVo.setImg(item.getProductImg());
            stockInProductItemVo.setPositions(warehouseBin.getId());
//            stockInProductItemVo.setUnitPrice(purchaseOrderProduct.getUnitPrice());
//            stockInProductItemVo.setCostPrice(purchaseOrderProduct.getCostPrice());
//            stockInProductItemVo.setMainUnitPrice(purchaseOrderProduct.getMainUnitPrice());
//            stockInProductItemVo.setGramWeight(purchaseOrderProduct.getGramWeight());
//            stockInProductItemVo.setLaborCosts(purchaseOrderProduct.getLaborCosts());
//            stockInProductItemVo.setAccessoriesPrice(purchaseOrderProduct.getAccessoriesPrice());
//            stockInProductItemVo.setSubtotal(purchaseOrderProduct.getTotalPrice());
            stockInProductItemVo.setLxFnsku(item.getLxFnsku());
            stockInProductItemVo.setFnskuFnsku(item.getLxFnsku());
//            stockInProductItemVo.setLxPrice(item.getLxPrice());
//            stockInProductItemVo.setLxTotalPrice(purchaseOrderProduct.getLxTotalPrice());
            stockInProductItemVo.setUnitStock(item.getReceiptNum().intValue());//到货数量
            stockInProductItemVo.setQuantity(0);//可用数量
            stockInProductItemVo.setWaitQuantity(item.getReceiptNum().intValue());
//            stockInProductItemVo.setWaitPutaway(item.getReceiptNum().intValue());
            productList.add(stockInProductItemVo);
//            purchaseOrderProductService.updateById(purchaseOrderProduct);
        }
        Long sum2 = productList.stream().mapToLong(StockInProductItemVo::getWaitQuantity).sum();
        stock.setTotalNum(sum2.toString());
        stock.setProductList(productList);
        Long id = stockInService.create(stock);
        return id;
    }
}
